let board;
export const PlayGroundWidth = 220;
export const PlayGroundHeight = 180;
const BlockX = 4;
const BlockY = 4;
export const CanvasWidth = PlayGroundWidth * BlockX;
export const CanvasHeight = PlayGroundHeight * BlockY;

export const Canvas = {
    init() {
        let playground = document.querySelector("#playground");
        board = playground.getContext("2d");
    },
    draw(graphics = []) {
        clearRect({ x: 0, y: 0, w: CanvasWidth, h: CanvasHeight });
        graphics.forEach(graph => {
            if (graph.opt.type === "text") {
                // graph是一段text
                drawText({
                    text: graph,
                    opt: graph.opt,
                });
            } else {
                // graph是一个shape
                drawShape({
                    points: graph,
                    opt: graph.opt,
                });
            }
        });
    },
    destroy() {
        // do nothing
    },
};

function clearRect({ x = 0, y = 0, w, h }) {
    board.clearRect(x * BlockX, y * BlockY, w, h);
}
function drawShape({ points, opt }) {
    let { fillColor, strokeColor, lineWidth } = opt;
    if (!Array.isArray(points) || !points.length || !Array.isArray(points[0]) || !points[0].length) {
        return;
    }
    board.beginPath();
    board.moveTo(points[0][0] * BlockX, points[0][1] * BlockY);
    points.slice(1).forEach(p => {
        board.lineTo(p[0] * BlockX, p[1] * BlockY);
    });
    board.closePath();
    if (fillColor) {
        board.fillStyle = fillColor;
        board.fill();
    }
    if (strokeColor) {
        board.strokeStyle = strokeColor;
        board.lineWidth && (board.lineWidth = lineWidth);
        board.stroke();
    }
}
function drawText({ text, opt }) {
    board.font = opt.font;
    // board.strokeStyle = "#ffffff";
    board.strokeText(text, opt.x * BlockX, opt.y * BlockY);
}
